package com.example.controller;

import com.example.dto.LoginRequest;
import com.example.service.CaptchaService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private final CaptchaService captchaService;
    private final UserService userService;

    @Autowired
    public UserController(CaptchaService captchaService, UserService userService) {
        this.captchaService = captchaService;
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        // 1. 验证验证码
        if (!captchaService.validateCaptcha(request.getCaptchaId(), request.getCaptcha())) {
            Map<String,String> res = new HashMap<>();
            res.put("message", "验证码错误");
            return ResponseEntity.badRequest().body(res);
        }
        
        try {
            // 2. 执行登录
            Map<String, Object> result = userService.login(request.getUsername(), request.getPassword());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String,String> res = new HashMap<>();
            res.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(res);
        }
    }

    @GetMapping("/captcha")
    public ResponseEntity<Map<String, String>> getCaptcha() {
        return ResponseEntity.ok(captchaService.generateCaptcha());
    }
} 